package userlogic

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/login-rpc/login_rpc"

	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/dao/model"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/svc"
	config "gitee.com/liuxuezhan/ar-platform/login-rpc/pkg/code"
	"github.com/zeromicro/go-zero/core/logx"
)

type PasswordUpdateAdminLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPasswordUpdateAdminLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PasswordUpdateAdminLogic {
	return &PasswordUpdateAdminLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PasswordUpdateAdminLogic) PasswordUpdateAdmin(in *login_rpc.PasswordUpdateAdminRequest) (*login_rpc.PasswordUpdateAdminResponse, error) {
	var commonResp login_rpc.CommonResp
	if in.UserId == 0 || in.Password == "" {
		commonResp.Code = config.ParameterError
		commonResp.Message = "empty userId or password"
		return &login_rpc.PasswordUpdateAdminResponse{CommonResp: &commonResp}, nil
	}

	password, _ := model.NewAdminUserModel(l.ctx, l.svcCtx.Db).GetAdminUserPasswordByUserId(in.UserId)

	if password != HashPassword(in.Password) {
		commonResp.Code = config.ParameterError
		commonResp.Message = "wrong old password"
		return &login_rpc.PasswordUpdateAdminResponse{CommonResp: &commonResp}, nil
	}

	db := l.svcCtx.Db.Begin()
	err := model.NewAdminUserModel(l.ctx, db).UpdateAdminUserPassword(in.UserId, HashPassword(in.NewPassword))
	if err != nil {
		db.Rollback()
		commonResp.Code = config.DBError
		commonResp.Message = "failed to update password"
		return &login_rpc.PasswordUpdateAdminResponse{CommonResp: &commonResp}, nil
	}

	// 密码修改成功，修改用户token
	err = model.NewAdminLoginToken(l.ctx, db).CleanAllLoginTokenOfUser(in.UserId)
	if err != nil {
		db.Rollback()
		commonResp.Code = config.DBError
		commonResp.Message = "delete token failed"
		return &login_rpc.PasswordUpdateAdminResponse{CommonResp: &commonResp}, nil
	}
	db.Commit()
	return &login_rpc.PasswordUpdateAdminResponse{CommonResp: &commonResp}, nil
}
